package com.gulimall.order.web;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.gulimall.order.service.impl.OrderServiceImpl;
import com.gulimall.order.vo.PayAsyncVo;
import com.gulimall.order.vo.PayVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Rookie-6688
 * @Description
 * @Create 2021-05-11 14:19
 */
@Slf4j
@Controller
public class PayOrderController {
    @Resource
    private AlipayTemplate alipayTemplate;
    @Resource
    private OrderServiceImpl orderServiceImpl;

    @ResponseBody
    @GetMapping(value = "/aliPayOrder",produces = "text/html")
    public String pay(@RequestParam String orderSn) throws AlipayApiException {
        PayVo payVo = orderServiceImpl.getPayVo(orderSn);
        String pay = alipayTemplate.pay(payVo);
        log.info(pay+"---------");
        return pay;
    }

    /**
     * 支付宝支付完成后的异步通知，当异步通知返回 success 支付宝端则结束，并且会每隔一段时间重复发送异步请求直到返回success为止
     * @param asyncVo
     * @param request
     * @return
     * @throws AlipayApiException
     * @throws UnsupportedEncodingException
     */
    @ResponseBody
    @PostMapping(value = "/payed/notify")
    public String handleAlipayed(PayAsyncVo asyncVo, HttpServletRequest request) throws AlipayApiException, UnsupportedEncodingException {
        // 只要收到支付宝的异步通知，返回 success 支付宝便不再通知
        // 获取支付宝POST过来反馈信息
        //1、验签
        log.info("支付宝异步回调方法------------------------------");
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(),
                alipayTemplate.getCharset(), alipayTemplate.getSign_type()); //调用SDK验证签名

        if (signVerified) {
            System.out.println("签名验证成功...");
            //2、当签名验证成功再执行相关的业务
            String result = orderServiceImpl.handlePayResult(asyncVo);
            return result;
        } else {
            System.out.println("签名验证失败...");
            return "error";
        }
    }
//
//    @PostMapping(value = "/pay/notify")
//    public String asyncNotify(@RequestBody String notifyData) {
//        //异步通知结果
//        return orderServiceImpl.asyncNotify(notifyData);
//    }

}
